/*
 * Copyright 2018-2022 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.gnu.org/licenses/lgpl-3.0.html
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.guerlab.cloud.gateway.sentinel;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import reactor.core.publisher.Mono;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;

import net.guerlab.cloud.core.result.Fail;
import net.guerlab.cloud.core.result.Result;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;

/**
 * 自定义限流处理.
 *
 * @author guer
 */
public class CustomerBlockRequestHandler implements BlockRequestHandler {

	private static final String DEFAULT_BLOCK_MSG_PREFIX = "Blocked by Sentinel: ";

	private static Result<Void> buildErrorResult(Throwable ex) {
		return new Fail<>(DEFAULT_BLOCK_MSG_PREFIX + ex.getClass().getSimpleName(),
				HttpStatus.TOO_MANY_REQUESTS.value());
	}

	@Override
	public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
		return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.APPLICATION_JSON)
				.body(fromValue(buildErrorResult(ex)));
	}
}
